//
//  IMNetwoingFileTransfer.m
//  YuanXinNetWorking
//
//  Created by 晏德智 on 2016/12/15.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "IMNetwoingFileTransfer.h"
#import "YuanXinUploadFiles.h"
#import "UploadFileLoader.h"
#import "NetworkingManager.h"
#import "IMFileCache.h"

#define  defaultDownUrl @"FileDownService/down/file"

@implementation IMNetwoingFileTransfer

+ (instancetype)shareInstance{
    static IMNetwoingFileTransfer *_netwoingFileTransfer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _netwoingFileTransfer = [[self alloc] init];
    });
    
    return _netwoingFileTransfer;
}

- (NSURL *)getHttpURL:(NSURL *)url {
    NSURL *httpURL = url;
    if ([url.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame) {
        NSString *urlStr = url.absoluteString;
        NSString *httpStr = [NetworkingManager shareInstance].baseURL.absoluteString;
        httpStr = [httpStr stringByAppendingString:[NSString stringWithFormat:@"%@?parment=%@", defaultDownUrl, urlStr]]; // "http://" 调用 stringByAppendingPathComponent 会去掉 '/'
        httpURL = [NSURL URLWithString:httpStr];
    }
    return httpURL;
}

- (BOOL)downloadImage:(NSURL *)netUrl objectKey:(NSString *)objectKey{
    
    // http://www.yuanxin2015.com/yuanxinfiles/IMTest/Image/E30DBAF3FC2D4527AC455E72AF756413.jpeg
    
    NSString *url;
    if([netUrl.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame){
        //NSString *serverPath =  [netUrl.absoluteString substringFromIndex:@"YuanXin-File://".length];
        //url = [url stringByAppendingString:serverPath];
        url = [self getHttpURL:netUrl].absoluteString;
    } else {
        url = netUrl.absoluteString;
    }
    NSArray *firstSplit = [netUrl.absoluteString componentsSeparatedByString:@"/"];
    NSString *filename = [firstSplit lastObject];
    NSURL *cacheUrl = [NSURL URLWithString:[IMFileCache shareInstance].cachePath];
    NSURL *localUrl = [[NSURL alloc] initWithString:filename relativeToURL:cacheUrl];
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask = nil;
    __block NSString *tag;
    if(objectKey){
        tag = [objectKey copy];
    }else {
        tag = filename;
    }
    dataTask = [[NetworkingManager shareInstance]
                downloadImageFile:url
                cacheURL:localUrl
                downloadProgress:nil
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onDownloadFileSucess:tag result:responseObject];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onError:tag error:error];
                    }
                }];
    return YES;
}

- (BOOL)downloadAudioFile:(NSURL *)netUrl objectKey:(NSString *)objectKey{
    
    NSString *url;
    if([netUrl.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame){
        //NSString *serverPath =  [netUrl.absoluteString substringFromIndex:@"YuanXin-File://".length];
        //url = [url stringByAppendingString:serverPath];
        url = [self getHttpURL:netUrl].absoluteString;
    } else {
        url = netUrl.absoluteString;
    }
    NSArray *firstSplit = [netUrl.absoluteString componentsSeparatedByString:@"/"];
    NSString *filename = [firstSplit lastObject];
    
    //这里要返回一个NSURL，其实就是文件的位置路径
    /*
     NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
     //使用建议的路径
     path = [path stringByAppendingPathComponent:filename];
     //NSURL *cacheUrl = [NSURL URLWithString:[IMFileCache shareInstance].cachePath];
     NSURL *localUrl = [NSURL URLWithString:path];
     */
    
    NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSURL *localUrl = [cachesDirectoryURL URLByAppendingPathComponent:filename];
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask = nil;
    __block NSString *tag;
    if(objectKey){
        tag = [objectKey copy];
    }else {
        tag = filename;
    }
    dataTask = [[NetworkingManager shareInstance]
                downloadFile:url
                headerAccept:@"audio/amr"
                cacheURL:localUrl
                downloadProgress:nil
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onDownloadFileSucess:tag result:responseObject];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onError:tag error:error];
                    }
                }];
    return YES;
}

- (void)downloadAudioFile:(NSURL *)netUrl
              toLocalPath:(NSString *)localPath
                  success:(void (^)(NSURL *fileURL))success
                  failure:(void (^)(NSError *error))failure {
    
    [self downloadFile:netUrl headerAccept:@"audio/amr" toLocalPath:localPath success:success failure:failure];
}

//downloadFile
- (BOOL)downloadFile:(NSURL *)netUrl objectKey:(NSString *)objectKey toLocalPath:(NSString *)localPath {
    
    NSString *url;
    if([netUrl.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame){
        url = [self getHttpURL:netUrl].absoluteString;
    } else {
        url = netUrl.absoluteString;
    }
    NSArray *firstSplit = [netUrl.absoluteString componentsSeparatedByString:@"/"];
    NSString *filename = [firstSplit lastObject];
    
    //这里要返回一个NSURL，其实就是文件的位置路径
    /*
     NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
     //使用建议的路径
     path = [path stringByAppendingPathComponent:filename];
     //NSURL *cacheUrl = [NSURL URLWithString:[IMFileCache shareInstance].cachePath];
     NSURL *localUrl = [NSURL URLWithString:path];
     */
    
    NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSURL *localUrl = [cachesDirectoryURL URLByAppendingPathComponent:filename];
    if (localPath) {
        localUrl = [NSURL fileURLWithPath:localPath];
    }
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *dataTask = nil;
    __block NSString *tag;
    if(objectKey){
        tag = [objectKey copy];
    }else {
        tag = filename;
    }
    dataTask = [[NetworkingManager shareInstance]
                downloadFile:url
                headerAccept:nil
                cacheURL:localUrl
                downloadProgress:nil
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onDownloadFileSucess:tag result:responseObject];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if(weakSelf.delegate){
                        [weakSelf.delegate onError:tag error:error];
                    }
                }];
    return YES;
}

//downloadFile
- (void)downloadFile:(NSURL *)netUrl
         toLocalPath:(NSString *)localPath
             success:(void (^)(NSURL *fileURL))success
             failure:(void (^)(NSError *error))failure {
    
    [self downloadFile:netUrl headerAccept:nil toLocalPath:localPath success:success failure:failure];
}

//downloadFile
- (void)downloadFile:(NSURL *)netUrl
        headerAccept:(NSString *)headerAccept
         toLocalPath:(NSString *)localPath
             success:(void (^)(NSURL *fileURL))success
             failure:(void (^)(NSError *error))failure {
    
    NSString *url;
    if([netUrl.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame){
        url = [self getHttpURL:netUrl].absoluteString;
    } else {
        url = netUrl.absoluteString;
    }
    NSArray *firstSplit = [netUrl.absoluteString componentsSeparatedByString:@"/"];
    NSString *filename = [firstSplit lastObject];
    
    //这里要返回一个NSURL，其实就是文件的位置路径
    /*
     NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
     //使用建议的路径
     path = [path stringByAppendingPathComponent:filename];
     //NSURL *cacheUrl = [NSURL URLWithString:[IMFileCache shareInstance].cachePath];
     NSURL *localUrl = [NSURL URLWithString:path];
     */
    
    NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    NSURL *localUrl = [cachesDirectoryURL URLByAppendingPathComponent:filename];
    if (localPath) {
        localUrl = [NSURL fileURLWithPath:localPath];
    }
    
    NSURLSessionDataTask *dataTask = nil;
    dataTask = [[NetworkingManager shareInstance]
                downloadFile:url
                headerAccept:headerAccept
                cacheURL:localUrl
                downloadProgress:nil
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    if(success){
                        success(localUrl);
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if(failure){
                        failure(error);
                    }
                }];
}

- (BOOL)uploadFile:(FileUploadInfo *)fileInfo{
    
    __weak typeof(self) weakSelf = self;
    __block  FileUploadInfo *upFileInfo = fileInfo;
    [[UploadFileLoader shareInstance] loaderFile:fileInfo successBlock:^(NSData *fileData, NSString *pathExtension) {
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        __block NSString *objecKey =fileInfo.objectKey;
        NSData *formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", objecKey] dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableData* reqBody = [NSMutableData data];
        // add fields
        [reqBody appendData:formBoundaryData];
        [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"bucketName"] dataUsingEncoding:NSUTF8StringEncoding]];
        [reqBody appendData:[[NetworkingManager shareInstance].bucketNameForIMUploadFile dataUsingEncoding:NSUTF8StringEncoding]];
        
        [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [reqBody appendData:formBoundaryData];
        [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"storageType"] dataUsingEncoding:NSUTF8StringEncoding]];
        [reqBody appendData:[[[NSNumber numberWithInteger:byFileType] stringValue] dataUsingEncoding:NSUTF8StringEncoding]];
        [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [reqBody appendData:formBoundaryData];
        [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"resourceID"] dataUsingEncoding:NSUTF8StringEncoding]];
        [reqBody appendData:[objecKey dataUsingEncoding:NSUTF8StringEncoding]];
        [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSString *fileName = [NSString stringWithFormat:@"%@.%@",upFileInfo.objectKey,pathExtension];
        NSString *contentType = [[UploadFileLoader shareInstance] mimeTypeForFilePath:fileName];
        NSData *data = [[UploadFileLoader shareInstance] appendFileFormData:fileData fileName:fileName contentType:contentType formBoundary:formBoundaryData];
        [reqBody appendData:data];
        
        NSData* end = [[NSString stringWithFormat:@"--%@--\r\n", objecKey] dataUsingEncoding:NSUTF8StringEncoding];
        [reqBody appendData:end];
        
        NSString *upContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", fileInfo.objectKey];
        NSDictionary *headrs = @{@"Content-Type":upContentType,
                                 @"Accept":@"application/json"};
        [[NetworkingManager shareInstance] uploadFile:@"FileUploadService/api/upload"
                                                 data:reqBody
                                               headers:headrs
                                               success:^(NSURLSessionDataTask *task, id _Nullable responseObject){
                                                   if(strongSelf.delegate){
                                                       [strongSelf.delegate onUploadFileSucess:objecKey result:responseObject];
                                                   }
                                               }
                                               failure:^(NSURLSessionDataTask * _Nullable task, NSError *error){
                                                   if(strongSelf.delegate){
                                                       [strongSelf.delegate onError:objecKey error:error];
                                                   }
                                               }];
     } failureBlock:^(NSError *error) {
         if(weakSelf.delegate){
             [weakSelf.delegate onError:upFileInfo.objectKey error:error];
         }
     }];
    
    return YES;
}

@end
